<template>
  <view>
    <view>
      <image
        style="width: 750rpx"
        src="@/static/images/login/login.jpg"
        mode="aspectFill"
      ></image>
    </view>
    <view class="main-card bg-white" style="padding: 0 32rpx; height: 765rpx">
      <view class="headshot flex-center">
        <view class="radius">
          <image
            style="width: 100%; height: 100%"
            class="flex-center"
            src="@/static/images/login/headshot.png"
            mode="aspectFill"
          ></image>
        </view>
      </view>
      <view class="form justify-center">
        <u--form :model="formData" :rules="customFormRules" ref="customForm">
          <!--  uniapp的input 输入不能清除和右边开始 所以一定要用ui框架 如uview-->
          <view class="align-center form-item">
            <!-- <text class="form-label"> -->
            <image
              class="form-icon"
              src="@/static/images/login/qiye.png"
            ></image>
            <!-- </text> -->
            <u-form-item prop="Hotel_id">
              <u-input
                disabledColor="'#ccc'"
                :custom-style="customInputStyle"
                placeholder="酒店编号"
                v-model="formData.Hotel_id"
                maxlength="20"
                style="background: none"
                :clearable="true"
              />
            </u-form-item>
          </view>

          <view class="align-center form-item">
            <!-- <text class="form-label"> -->
            <image
              class="form-icon"
              src="@/static/images/login/name.png"
            ></image>
            <!-- </text> -->
            <u-form-item prop="Name">
              <u-input
                :custom-style="customInputStyle"
                placeholder="请输入账号/手机号"
                v-model="formData.Name"
                maxlength="20"
                style="background: none"
                :clearable="true"
              />
            </u-form-item>
          </view>

          <view class="align-center form-item">
            <!-- <text class="form-label"> -->
            <image
              class="form-icon"
              src="@/static/images/login/mima.png"
            ></image>
            <!-- </text> -->
            <u-form-item prop="Pwd">
              <u-input
                :custom-style="customInputStyle"
                placeholder="请输入密码"
                v-model="formData.Pwd"
                maxlength="20"
                style="background: none"
                :password="isPassword"
                :clearable="false"
              />
              <template #right>
                <view @click="isPassword = !isPassword">
                  <image
                    v-show="isPassword"
                    class="form-icon"
                    style="height: 28rpx"
                    src="@/static/images/login/eye-solid.png"
                  ></image>
                  <image
                    v-show="!isPassword"
                    class="form-icon"
                    style="height: 28rpx"
                    src="@/static/images/login/eye-slash.png"
                  ></image>
                </view>
              </template>
            </u-form-item>
          </view>

          <view class="align-center form-item">
            <text class="form-label"></text>
            <u-form-item prop="ValidCode">
              <u-input
                :custom-style="customInputStyle"
                placeholder="请输入验证码"
                v-model="formData.ValidCode"
                maxlength="4"
                style="background: none"
                :clearable="false"
              />
              <template #right>
                <view
                  class="align-center validCodeImg"
                  @click="onValidCode()"
                  style="
                    position: relative;
                    left: -95rpx;
                    width: 186rpx;
                    height: 66rpx;
                  "
                >
                  <image
                    style="width: 100%; height: 100%"
                    ref="ValidCodeImgRef"
                    :src="ValidCodeImg"
                  ></image>
                  <view class="refresh" v-show="isValidRefresh">
                    <view class="flex-center" style="height: 100%">
                      <image
                        style="width: 40rpx; height: 40rpx"
                        src="@/static/images/login/refresh.png"
                      />
                    </view>
                  </view>
                </view>
              </template>
            </u-form-item>
          </view>

          <u-button type="primary" text="确定" @click="submit"></u-button>
        </u--form>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import customFormRules from './register_formRules'
import { getSessionCode, set_access_token } from '@/storage/global'
import {
  ValidCode,
  INF_ValidCode_res,
  INF_Login_params,
  Login,
  INF_Login_res
} from '@/api/server/v2/login'
import { GetHotelName } from '@/api/server/v1/user'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import CryptoJS from 'crypto-js'
import route from '@/utils/route'
import { getUserInfo, INF_UserInfo, setUserInfo } from '@/storage/login'
import { loginPage_index } from '@/route'

let timer: any = null
let ValidTimerCount: number = 0
const ValidCodeImg = ref<string>('')
const ValidTimeout: number = 60 // 60秒刷新
let isValidRefresh = ref<boolean>(false)
const isAddUser = ref<boolean>(false)
const customForm = ref<string>('')
const customInputStyle = reactive({
  color: '#333333',
  fontSize: '28rpx'
})

const formData: INF_Login_params = reactive({
  Hotel_id: '', // 酒店编号 string
  Name: '', // 酒店名称 string
  Pwd: '', // 密码
  Token: '', // 验证码的token
  ValidCode: '', // 验证码
  SessionCode: '' // 临时token
})

const isPassword = ref<boolean>(true)

const onValidCode = function () {
  ValidCode().then((res) => {
    const result: INF_ValidCode_res = res as INF_ValidCode_res
    ValidCodeImg.value = 'data:image/jpeg;base64,' + result.ValidCodeImg
    formData.Token = result.Token
    isValidRefresh.value = false
    formData.SessionCode = getSessionCode()
  })
}
const onLogin = function () {
  const origin_UserInfo: INF_UserInfo = getUserInfo()
  // 重新输入了，点击登录就重新设置下UserInfo, 因为即刻就要带着输入的 Hotel_Id 塞请求头了
  const UserInfo: INF_UserInfo = {
    UserName: formData.Name,
    HotelId: formData.Hotel_id,
    HotelName: ''
  }
  setUserInfo(UserInfo)
  const Pwd = CryptoJS.enc.Base64.stringify(
    CryptoJS.enc.Hex.parse(CryptoJS.SHA256(formData.Pwd).toString())
  )
  Login({ ...formData, Pwd })
    .then((res) => {
      const result = res as INF_Login_res
      set_access_token(result.access_token)
      // 登录成功了，单独请求下接口获取HotelName, 因为此接口需要set_access_token的
      GetHotelName().then((info) => {
        const r = info as { HotelName: string }
        setUserInfo({
          UserName: formData.Name,
          HotelId: formData.Hotel_id,
          HotelName: r.HotelName
        })
      })
      if (isAddUser.value) {
        route.$route_reLaunch(loginPage_index)
      } else {
        route.$routeTo_tabbar('/pages/home/index')
      }
    })
    .catch(() => {
      //   失败了要重新存会原来的UserInfo
      // 并且刷新验证码
      setUserInfo(origin_UserInfo)
      onValidCode()
    })
}

// 分割成每60秒置灰验证码
const splitValidCodeIcon = function () {
  timer = setInterval(() => {
    if (ValidTimerCount >= ValidTimeout) {
      ValidTimerCount = 0
      isValidRefresh.value = true
      clearInterval(timer)
    } else {
      ValidTimerCount++
    }
  }, 1000)
}
const submit = function () {
  customForm.value
    .validate()
    .then(() => {
      onLogin()
    })
    .catch((_) => {
      console.log(_, '校验错误')
    })
}

// 生命周期
onLoad((routeParams) => {
  const r = routeParams as { add?: string }
  isAddUser.value = !!r.add
  onValidCode()
  splitValidCodeIcon()
})

onUnload(() => {
  uni.showTabBar({
    fail: () => {
      // 捕获报错，防止没有tabbar页面调用后控制台报错
    }
  })
})
</script>

<style lang="scss" scoped>
.main-card {
  .validCodeImg {
    position: relative;
    cursor: pointer;

    .refresh {
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      background: #000000;
      opacity: 0.66;
    }
  }
  // headhost头像
  .headshot {
    margin-top: -50rpx;

    .radius {
      background: #ffffff;
      width: 128rpx;
      padding: 12rpx;
      height: 128rpx;
      z-index: 2;
    }
  }

  // form表单
  .form {
    .form-icon {
      width: 38rpx;
      height: 38rpx;
    }

    ::v-deep {
      .u-form {
        width: 70%;
      }

      .u-form-item__body__right__message,
      .u-modal__content {
        text-align: left;
      }

      // 禁用的动态样式
      .form-disabled {
        color: #999999;

        view,
        text {
          color: #999999 !important;
        }
      }
    }

    .form-item {
      border-bottom: 2rpx solid #ebebeb;

      .form-label {
        width: 34rpx;
        padding-right: 10rpx;
        white-space: nowrap;
        font-size: 28rpx;
      }
    }
  }
}

:deep(.u-form-item__body__right__message) {
  position: relative;
  top: -15rpx;
  margin-left: 20rpx !important;
}
</style>
